package com.keycloak.admin.services;

import com.keycloak.admin.config.Myprops;
import com.keycloak.admin.model.params.ReturnParams;
import com.keycloak.admin.model.params.vo.RefreshTokenReturn;
import com.keycloak.admin.utils.ConnectSingleUtils;
import com.keycloak.admin.utils.MainServerUtils;
import com.keycloak.admin.utils.PayCallBackUtil;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Service
public class RequestPostCallbackService {

    @Resource
    Myprops myProps;

    @Resource
    MainServerUtils mainServerUtils;


   // private Unirest unirest =new Unirest();

   public String refreshToken(String url,Map<String ,Object> map,String token){

       try {
           System.out.println(url);
           String  result = null;
           try {
               result = PayCallBackUtil.net(url, map, "POST",token);
               JSONObject object = JSONObject.fromObject(result);
               if (object.getInt("code") == 0) {
               } else {
                   System.out.println(object.get("code") + ":" + object.get("msg"));
               }
           } catch (Exception e) {
               e.printStackTrace();
           }

           return result;

       } catch (Exception e) {
           e.printStackTrace();
       }
       return null;

   }


   //解析用户信息
    public ReturnParams getKeycloakUserInfoByAccessToken(String realmName,String clientId,String clientSecrt,String token){
        HttpResponse<String> response = null;
        try {
            response = getKeycloakUserInfo(realmName, clientId, clientSecrt, token);
            if(response == null ){
                response = getKeycloakUserInfo(realmName, clientId, clientSecrt, token);
            }
            if(response !=null && response.getStatus() == 200){
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response.getBody());
                if(jsonObject.containsKey("active")){
                    if("false".equalsIgnoreCase(jsonObject.getString("active"))){
                        //token 失效
                        return new ReturnParams(999,"token 失效！!",null);
                    }
                }  ;
                return new ReturnParams(0,"成功",com.alibaba.fastjson.JSONObject.parseObject(response.getBody()));
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnParams(1,"解析失败!",null);
    }

   public HttpResponse<String>  getKeycloakUserInfo(String realmName,String clientId,String clientSecrt,String token) throws IOException{
       HttpResponse<String> response = null;

       try {
           response = ConnectSingleUtils.getInstance().post(myProps.getKeycloakUrl()+"/auth/realms/"+realmName+"/protocol/openid-connect/token/introspect")
                   .header("Content-Type", "application/x-www-form-urlencoded")
                   .field("client_id", clientId)
                   .field("client_secret", clientSecrt)
                   .field("token", token)
                   .asString();
           System.out.println(response);
           if(response != null ){
               System.out.println("返回状态值： "+response.getStatus());
           }
           return response;

       } catch (Exception e) {
           e.printStackTrace();
           return null;
       }

   }


   public ReturnParams getUserInfoByAccessToken(String realmName,String clientId,String clientSecrt,String token){
       HttpResponse<String> response = null;

       try {
            response = getKeycloakUserInfo(realmName, clientId, clientSecrt, token);
            if(response == null ){
                response = getKeycloakUserInfo(realmName, clientId, clientSecrt, token);
            }

           if(response !=null && response.getStatus() == 200){
               com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response.getBody());
               if(jsonObject.containsKey("active")){
                   if("false".equalsIgnoreCase(jsonObject.getString("active"))){
                       //token 失效
                       return new ReturnParams(999,"无效token，请重新登陆获取!",null);
                   }
               }  ;
               String username = com.alibaba.fastjson.JSONObject.parseObject(response.getBody()).getString("username");
               if(username == null){
                   return new ReturnParams(1,"用户不存在！",null);
               }
               System.out.println(username);
               return new ReturnParams(0,username,null);
           }
           return new ReturnParams(1,"解析token异常！",response== null?null:response.getStatus()+":--:"+response== null?null:response.getBody());
       } catch (Exception e) {
           e.printStackTrace();
           return new ReturnParams(1,"系统异常!",null);
       }

   }

   public ReturnParams refreTokenPostman(String accessToken,String clientId,String realmName){
       try {

           HttpResponse<String> stringHttpResponse = ConnectSingleUtils.getInstance().post(myProps.getKeycloakUrl()+"/auth/realms/"+realmName+"/protocol/openid-connect/token")
                   .header("Content-Type", "application/x-www-form-urlencoded")
                   .header("Authorization", "Bearer "+accessToken)
                   .field("audience", clientId)
                   .field("response_include_resource_name", "true")
                   .field("grant_type", "urn:ietf:params:oauth:grant-type:uma-ticket")
                   .asString();
           HttpResponse<String> response = stringHttpResponse;
           System.out.println(response);
          // Unirest.
          /* HttpResponse<RefreshTokenReturn> bookResponse = Unirest.get("http://httpbin.org/books/1").asObject(RefreshTokenReturn.class);
           RefreshTokenReturn bookObject = bookResponse.getBody();
*/
           if(response.getStatus() != 200){
               return new ReturnParams(1,"error",com.alibaba.fastjson.JSONObject.parseObject(response.getBody()));

           }else{
               return new ReturnParams(0,"success",com.alibaba.fastjson.JSONObject.parseObject(response.getBody()));
           }


       } catch (Exception e) {
           e.printStackTrace();
           return null;
       }

   }


    public String refreTokenPostman1(String accessToken,String clientId,String realmName){
        try {
            HttpResponse<String> stringHttpResponse = ConnectSingleUtils.getInstance().post(myProps.getKeycloakUrl()+"/auth/realms/"+realmName+"/protocol/openid-connect/token")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .header("Authorization", "Bearer "+accessToken)
                    .field("audience", clientId)
                    .field("response_include_resource_name", "true")
                    .field("grant_type", "urn:ietf:params:oauth:grant-type:uma-ticket")
                    .asString();
            HttpResponse<String> response = stringHttpResponse;
            System.out.println(response);

          /* HttpResponse<RefreshTokenReturn> bookResponse = Unirest.get("http://httpbin.org/books/1").asObject(RefreshTokenReturn.class);
           RefreshTokenReturn bookObject = bookResponse.getBody();
*/
            if(response.getStatus() == 200){
                return com.alibaba.fastjson.JSONObject.parseObject(response.getBody()).get("access_token").toString();
            }else{
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }


}
